package org.lucky.admin.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.lucky.admin.util.RedisUtil;
import org.lucky_common.dto.AdminDto;
import org.lucky_common.util.AjaxResult;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Nonnull;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录拦截
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;


    /**
     * 登录拦截,如果没有登录就要返回错误信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, @Nonnull Object handler) throws Exception {
        // 1 获取请求头中的token
        String token = request.getHeader("TOKEN");
        response.setContentType("application/json;charset=UTF-8");

        // 2 如果token为空,说明未登录,要返回错误信息并拦截
        if(StringUtils.isBlank(token)){
            AjaxResult ajaxResult = AjaxResult.error("noLogin");
            response.getWriter().print(JSONObject.toJSONString(ajaxResult));
            return false;
        }

        // 3 根据token作为key,去redis中获取登录信息
        //与redis里的key比较是否存在
        System.out.println("111111");
        System.out.println(token);
        AdminDto employee = redisUtil.getKey(token);
        if (employee == null){
            PrintWriter out = response.getWriter();
            //返回json {"success":true,"message":"请登录","data":"noAuth"}
            out.println("{\"success\":false,\"msg\":\"请登录\",\"data\":\"noLogin\"}");
            out.flush();
            out.close();
            //拦截
            return false;
        }
        // 如果不为空,说明已经登录过就放行,并且重新给该key所在的redis设置30分钟过期时间
        redisUtil.setex(token, employee,2*60*60);
        return true;
    }
}
